package cn.yunhe.controller;

import cn.yunhe.model.User;
import cn.yunhe.service.impl.UserServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * @创建人 项目二组 鲍康
 * @创建时间 2018/1/7
 * @描述
 */
@RestController
@RequestMapping("/shiro")
public class ShiroController {

    @Resource
    private UserServiceImpl userService;

    @RequestMapping("/login")
    public ModelAndView login(User user, HttpSession session){
        ModelAndView mv = new ModelAndView();
        mv.setView(new MappingJackson2JsonView());
        //1.创建subject实例
        Subject currentUser = SecurityUtils.getSubject();
        //2.判断当前用户是否登录
        if(!currentUser.isAuthenticated()){
            //将用户名密码封装UsernamePasswordToken
            UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(),user.getPassword());
            try {
                currentUser.login(token);
            } catch ( AuthenticationException ae ) {
                //认证异常
                //无法判断的情形
                mv.setViewName("regist");
                return mv;
            }
        }
        mv.setViewName("index");
        return mv;
    }


    @RequestMapping("/aaa")
    public ModelAndView aaa(){
        ModelAndView mv = new ModelAndView();
        mv.setView(new MappingJackson2JsonView());
        User user  = userService.queryUsername(new User("bk","bk"));
        System.out.println(user.getUsername());
        return mv;
    }


    public UserServiceImpl getUserService() {
        return userService;
    }

    public void setUserService(UserServiceImpl userService) {
        this.userService = userService;
    }
}
